package com.heima.user.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.user.mapper.ApUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;


@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {



    /**
     * 登录
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.正常登录（手机号+密码登录）
        String password = loginDto.getPassword();
        String phone = loginDto.getPhone();
        //1.1查询用户
        if (!StringUtils.isBlank(phone) && !StringUtils.isBlank(password)) {
            ApUser apUser = this.getOne
                    (Wrappers.lambdaQuery(ApUser.class).eq(ApUser::getPhone, loginDto.getPhone()));

            if (apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"手机号不存在");
            }
            //1.2 比对密码
            String salt = apUser.getSalt();
            String psw = apUser.getPassword();
            password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (!psw.equals(password)){
                ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //1.3 返回数据  jwt
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            HashMap<String, Object> map = new HashMap<>();
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user",apUser);
            map.put("token",token);
            return ResponseResult.okResult(map);

        }else {
            //2.游客  同样返回token  id = 0
            String token = AppJwtUtil.getToken(0L);
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }

    }
}
